package com.noble.meether.logic.center;

import android.content.Context;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.widget.EditText;

import com.alibaba.fastjson.JSON;
import com.noble.glamour.bean.center.user.detail.UserDetail;
import com.noble.glamour.module.local.chat.utils.MsgUtils;
import com.noble.glamour.module.logic.application.ModuleMgr;
import com.noble.glamour.module.logic.baseui.LoadingDialog;
import com.noble.glamour.module.logic.config.InfoConfig;
import com.noble.glamour.module.logic.config.UrlParam;
import com.noble.glamour.module.logic.request.RequestComplete;
import com.noble.glamour.module.logic.socket.IMProxy;
import com.noble.library.dir.DirType;
import com.noble.library.log.PLogger;
import com.noble.library.log.PSP;
import com.noble.library.log.PToast;
import com.noble.library.observe.ModuleBase;
import com.noble.library.observe.MsgMgr;
import com.noble.library.observe.MsgType;
import com.noble.library.observe.PObserver;
import com.noble.library.utils.BitmapUtil;
import com.noble.library.utils.FileUtil;
import com.noble.library.utils.StringUtils;
import com.noble.library.utils.TypeConvertUtil;
import com.noble.meether.MeetUIShow;
import com.noble.meether.chat.ui.imui.util.IMChatUtil;
import com.noble.meether.logic.media.MediaConstant;
import com.noble.meether.logic.media.UpLoadResult;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 个人中心管理类
 */
public class CenterMgr implements ModuleBase, PObserver {
    private static final String INFO_SAVE_KEY = "MEET_INFO_SAVE"; // 本地化个人资料key
    private UserDetail userDetail = null;

    private boolean isUploadAvatar = false;     // 是否更新头像
    private static String tempAvatar = "";     // 临时设置头像地址，当头像有更新时，删除服务端旧头像文件
    private static String tempUploadUrl = "";  // 临时上传文件地址，当更新失败，该文件即不会在被应用，执行删除

    private boolean isGetNumFriendAsk = false;

    @Override
    public void init() {
        MsgMgr.getInstance().attach(this);
    }

    @Override
    public void release() {
        MsgMgr.getInstance().detach(this);
    }

    @Override
    public void onMessage(String key, Object value) {
        switch (key) {
            case MsgType.MT_App_Login:
                if ((Boolean) value) {
                    IMChatUtil.getInstance().queryMsgDBList();  // 登录成功，读取信箱消息列表
                    login();
                } else {
                    IMProxy.getInstance().logout();//退出登录的时候退出socket
                    clearUserInfo();
                }
                break;

            case MsgType.MT_App_IMStatus://socket登录成功后取离线消息
//                HashMap<String, Object> data = (HashMap<String, Object>) value;
//                int type = (int) data.get("type");
//                if (type == TCPConstant.SOCKET_STATUS_Login_Success) {
//                    ModuleMgr.getOfflineMgr().getOfflineMsg();
//                }
                break;

            case MsgType.MT_Update_MyInfo:
                reqMyInfo("CenterMgr.MT_Update_MyInfo");
                break;
            case MsgType.MT_MyInfo_Change:
                // 申请未读角标
                if (userDetail.getNumFriendAsk() > 0 && !isGetNumFriendAsk) {
                    isGetNumFriendAsk = true;
                    MsgUtils.handleAskFriend(userDetail.getNumFriendAsk(), true);
                }
                break;
            default:
                break;
        }
    }

    private void login() {
        reqMyInfo(response -> {
            ModuleMgr.getCommonMgr().reqMsgServer();

            // 设置推送参数
            if (userDetail != null){
                ModuleMgr.getPushMgr().setJPushAlias(userDetail.getUid());
            }
        }, "CenterMgr.MT_App_Login");
    }

    /**
     * 获取我的个人资料
     */
    public UserDetail getMyInfo() {
        if (userDetail == null) {
            userDetail = new UserDetail();
            String result = PSP.getInstance().getString(INFO_SAVE_KEY, "");
            if (!TextUtils.isEmpty(result)) {
                userDetail.parseJson(result);
            }
        }
        return userDetail;
    }

    public void reqMyInfo(String channel) {
        reqMyInfo(null, channel);
    }

    /**
     * 获取自己的个人资料
     */
    public void reqMyInfo(final RequestComplete complete, String channel) {
        PLogger.d("reqInfo:  资料请求来源:: " + channel);

        ModuleMgr.getHttpMgr().reqGetNoCacheHttp(UrlParam.reqMyInfo, null, response -> {
            if (response.isOk()) {
                userDetail = (UserDetail) response.getBaseData();
                tempAvatar = userDetail.getAvatar();        // 更新临时头像地址
                setMyInfo(response.getResString());         // 保存到SP
                MsgMgr.getInstance().sendMsg(MsgType.MT_MyInfo_Change, null);
            }
            if (complete != null) {
                complete.onRequestComplete(response);
            }
        });
    }

    /**
     * 按需拿个人资料数据
     */
    public void reqMyPartInfo(String[] field, final RequestComplete complete) {
        HashMap<String, Object> param = new HashMap<>();
        param.put("fields", JSON.toJSONString(field));
        ModuleMgr.getHttpMgr().reqGetNoCacheHttp(UrlParam.reqMyInfo, param, response -> {
            if (complete != null) {
                complete.onRequestComplete(response);
            }
        });
    }

    // ================================== 修改资料 ==================================================

    /**
     * 重置好友申请未读角标
     */
    public void updateAskFriendUnread() {
        HashMap<String, Object> param = new HashMap<>();
        param.put(EditKey.s_key_askFriend, 0);
        updateMyInfo(false, param, null);
    }

    /**
     * 修改个人信息
     */
    public void updateMyInfo(final HashMap<String, Object> params, final RequestComplete complete) {
        updateMyInfo(true, params, complete);
    }

    public void updateMyInfo(final boolean showToast, final HashMap<String, Object> params, final RequestComplete complete) {
        ModuleMgr.getHttpMgr().reqJsonNoCacheHttp(UrlParam.reqModifyInfo, params, response -> {
            LoadingDialog.closeLoadingDialog(200);
            if (complete != null) complete.onRequestComplete(response);
            if (showToast)
                PToast.showShort(response.getMsg());

            if (response.isOk()) {
                // 头像有更新, 删除服务端过时头像文件
                if (isUploadAvatar && !TextUtils.isEmpty(tempAvatar)) {
                    ModuleMgr.getMediaMgr().sendDeleteFile(tempAvatar, null);
                }
                reqMyInfo("CenterMgr.updateMyInfo()");
            } else {    // 更新失败, 把上传头像文件清除
                if (isUploadAvatar && !TextUtils.isEmpty(tempUploadUrl)) {
                    ModuleMgr.getMediaMgr().sendDeleteFile(tempUploadUrl, null);
                }
            }
            isUploadAvatar = false;
        });
    }

    /**
     * 上传头像
     */
    public void uploadAvatar(final String url, final RequestComplete complete) {
        final String smallPath = BitmapUtil.getSmallBitmapAndSave(url, DirType.getUploadDir());
        if (FileUtil.isExist(smallPath)) {
            ModuleMgr.getMediaMgr().sendHttpFile(MediaConstant.UPLOAD_TYPE_AVATAR, smallPath, response -> {
                LoadingDialog.closeLoadingDialog();
                FileUtil.deleteFile(smallPath);

                PToast.showShort(response.getMsg());
                if (response.isOk()) {
                    isUploadAvatar = true;
                    UpLoadResult result = (UpLoadResult) response.getBaseData();
                    tempUploadUrl = result.getUploadUrl();
                    HashMap<String, Object> postParams = new HashMap<>();
                    postParams.put(EditKey.s_key_avatar, tempUploadUrl);
                    updateMyInfo(postParams, response1 -> {
                        if (complete != null) complete.onRequestComplete(response1);
                    });
                }
            });
        } else {
            LoadingDialog.closeLoadingDialog();
            PToast.showShort("图片地址无效");
        }
    }

    /**
     * 上传女性认证图片
     */
    public void uploadSexAuth(Context context, final String url, RequestComplete complete) {
        final String smallPath = BitmapUtil.getSmallBitmapAndSave(url, DirType.getUploadDir(), 320, 600);
        if (FileUtil.isExist(smallPath)) {
            ModuleMgr.getMediaMgr().sendHttpFile(MediaConstant.UPLOAD_TYPE_AUTH, smallPath, response -> {
                if (complete != null) {
                    complete.onRequestComplete(response);
                }
                LoadingDialog.closeLoadingDialog();
                FileUtil.deleteFile(smallPath);
                if (response.isOk()) {
                    PToast.showShort("恭喜您，认证成功");
                    userDetail.setStatusAuth(1);
                    return;
                }
                MeetUIShow.showSexAuthFailDlg((FragmentActivity) context, response.getMsg());
            });
        } else {
            LoadingDialog.closeLoadingDialog();
            PToast.showShort("图片地址无效");
        }
    }

    /**
     * 获取他人资料
     */
    public void reqOtherInfo(long otherId, final RequestComplete complete) {
        HashMap<String, Object> param = new HashMap<>();
        param.put("uid_to", otherId);
        ModuleMgr.getHttpMgr().reqGetNoCacheHttp(UrlParam.reqMyInfo, param, response -> {
            if (complete != null) {
                complete.onRequestComplete(response);
            }
        });
    }

    /**
     * 按需拿他人资料数据
     */
    public void reqOtherPartInfo(long otherId, String[] field, final RequestComplete complete) {
        HashMap<String, Object> param = new HashMap<>();
        param.put("fields", JSON.toJSONString(field));
        param.put("uid_to", otherId);
        ModuleMgr.getHttpMgr().reqGetNoCacheHttp(UrlParam.reqMyInfo, param, response -> {
            if (complete != null) {
                complete.onRequestComplete(response);
            }
        });
    }

    /**
     * 获取我的礼物列表
     */
    public void reqGetGift(int page, String month, RequestComplete complete) {
        Map<String, Object> param = new HashMap<>();
        param.put("dt_gift", 2);   // 礼物方向 默认1 送出=1 接收=2
        param.put("yearmonth", month);
        param.put("limit", 10);
        param.put("offset", 10 * (page - 1));
        ModuleMgr.getHttpMgr().reqGetNoCacheHttp(UrlParam.reqGetGift, param, complete);
    }

    // =================================== 暂时无用接口 ======================================

    /**
     * 清除用户信息
     */
    public void clearUserInfo() {
        userDetail = null;
        setMyInfo("");
    }

    /**
     * 昵称：个人资料限制昵称最大字数
     * 过滤空格 禁止注册的时候 昵称带有空格
     *
     * @param limit : 限制字数个数
     */
    public void inputFilterSpace(final EditText edit, final int limit) {
        edit.addTextChangedListener(new TextWatcher() {
            int cou = 0;
            int selectionEnd = 0;

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                cou = before + count;
                String editable = edit.getText().toString();
                String str = StringUtils.noSpace(editable);
                if (!editable.equals(str)) {
                    edit.setText(str);
                }
                edit.setSelection(edit.length());
                cou = edit.length();
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (cou > limit) {
                    selectionEnd = edit.getSelectionEnd();
                    s.delete(limit, selectionEnd);
                    if (!TextUtils.isEmpty(s)) {
                        edit.setText(s.toString());
                    }
                }
            }
        });
    }

    /**
     * 保存个人信息Json串到SP
     */
    private void setMyInfo(String resultStr) {
        PSP.getInstance().put(INFO_SAVE_KEY, resultStr);
    }

    /**
     * 图片上传时截取的字符串
     * <p>
     * 短存储： oss
     * 长存储： jxfile
     */
    public String getInterceptUrl(String picUrl) {
        if (TextUtils.isEmpty(picUrl)) return "";
        String tag = MediaConstant.STR_SHORT_TAG;
        if (picUrl.contains(MediaConstant.STR_LONG_TAG)) {
            tag = MediaConstant.STR_LONG_TAG;
        }
        return StringUtils.getAfterWithFlag(picUrl, tag);
    }

    // -------------------------充值页面逻辑 end---------------------------

    /**
     * 根据日期获取星座
     */
    private List<String> starList;
    private List<String> matchTable; // 配表

    public String getStar(int month, int day) {
        if (null == starList) {
            starList = InfoConfig.getInstance().getConstellation().getShow();
        }
        if (null == matchTable) {
            matchTable = InfoConfig.getInstance().getConstellation().getSubmit();
        }
        return day < TypeConvertUtil.toInt(matchTable.get(month - 1)) ? starList.get(month - 1) : starList.get(month);
    }
}